package org.example.test.es;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import javax.annotation.Resource;
import java.io.IOException;



@Slf4j
public class EsSearchUtil {



    private RestHighLevelClient client;
    public EsSearchUtil(){
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.50.130:9200")));
    }
    public SearchResponse matchContentQuery(String index, String query){

        // 构建搜索请求
        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 构建查询条件，这里使用 matchAllQuery 查询所有文档

        searchSourceBuilder.query(QueryBuilders.matchQuery("content", query));
        searchRequest.source(searchSourceBuilder);

        try {
            // 执行搜索请求
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            // 处理搜索结果
//            System.out.println("Total hits: " + searchResponse.getHits().getTotalHits().value);
//            searchResponse.getHits().forEach(hit -> {
//                System.out.println("Document ID: " + hit.getId());
//                System.out.println("Document source: " + hit.getSourceAsString());
//            });
            return searchResponse;
        } catch (Exception e) {
            log.error("",e);
        }
        return null;
    }

}

